package com.github.xzb617.adm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xzb617.adm.service.RouteRuleItemService;
import com.github.xzb617.adm.service.RouteRuleService;
import com.github.xzb617.domain.common.AjaxResponse;
import com.github.xzb617.domain.common.Page;
import com.github.xzb617.domain.common.PageData;
import com.github.xzb617.domain.common.PageTextCondition;
import com.github.xzb617.domain.dto.RouteDTO;
import com.github.xzb617.domain.entity.*;
import com.github.xzb617.domain.vo.RouteVO;
import org.springframework.web.bind.annotation.*;

import javax.validation.Validation;
import javax.validation.ValidationException;
import java.util.List;

/**
 * 路由规则控制器
 * @author xzb617
 */
@RestController
@RequestMapping("/route")
public class RouteRuleController {

    private final RouteRuleService routeRuleService;
    private final RouteRuleItemService routeRuleItemService;

    public RouteRuleController(RouteRuleService routeRuleService, RouteRuleItemService routeRuleItemService) {
        this.routeRuleService = routeRuleService;
        this.routeRuleItemService = routeRuleItemService;
    }


    @GetMapping("getById")
    public AjaxResponse getById(Integer id) {
        RouteRule routeRule = this.routeRuleService.getById(id);
        List<RouteRuleItem> routeRuleItems = this.routeRuleItemService.getListByRouteRuleId(id);
        return AjaxResponse.success().message("查询成功").data(new RouteVO(routeRule, routeRuleItems));
    }

    @GetMapping("/getList")
    public AjaxResponse getList(PageTextCondition condition) {
        PageHelper.startPage(condition.getPageNum(), condition.getPageSize());
        List<RouteRule> list = this.routeRuleService.getList(condition);
        PageInfo<RouteRule> pageInfo = new PageInfo<>(list);
        PageData<RouteRule> pageData = Page.toData(pageInfo);
        return AjaxResponse.success().message("查询成功").data(pageData);
    }

    @PutMapping("/update")
    public AjaxResponse update(@RequestBody RouteDTO dto) {
        if (dto.getRouteRuleItems().size() > 10) {
            throw new ValidationException("每个路由规则最多允许10个规则细项");
        }
        this.routeRuleService.update(dto);
        return AjaxResponse.success().message("更新成功");
    }
}
